package com.arcblock.demo.present


import android.util.Log
import com.arcblock.demo.constant.Constant.Companion.BASE_URL
import com.arcblock.demo.entity.Frontmatter
import com.arcblock.demo.http.IGetDataService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * p层
 */
open abstract class GetDataPresenter {
    val service: IGetDataService
    init {
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        service = retrofit.create<IGetDataService>(IGetDataService::class.java!!)
    }

    abstract fun transmitDatas(datas: List<Frontmatter>)

    val callback = object : Callback<List<Frontmatter>> {
        override fun onResponse(call: Call<List<Frontmatter>>?, response: Response<List<Frontmatter>>?) {
            if (response == null) {
                Log.e("main", "服务器没有成功返回")
            } else {
                if (response.isSuccessful()) {
                    val responseInfo = response.body()
                    if (responseInfo!=null && responseInfo.size>0) {
                        transmitDatas(responseInfo)
                    }
                } else {
                    Log.e("main", "服务器代码错误")
                }
            }
        }

        override fun onFailure(call: Call<List<Frontmatter>>?, t: Throwable?) {
            //没有连上服务器
            Log.e("main", "没有连上服务器")
        }
    }
}
